package huoye.shops.huoye.operation.activity;

import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.codeideology.android.previewimage.PrevieImage;
import com.codeideology.android.previewimage.PrevieImageActivity;
import com.codeideology.android.utils.BarUtils;
import com.codeideology.android.utils.DateTimeFormat;
import com.codeideology.android.utils.StringUtils;
import com.codeideology.android.widget.pickerview.TimePickerView;
import com.codeideology.android.widget.recycler.RecyclerViewAdapter;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import huoye.shops.R;
import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseTakePhotoActivity;
import huoye.shops.base.UserManager;
import huoye.shops.common.AddPictureAdapter;
import huoye.shops.common.ImageTextAdapter;
import huoye.shops.common.model.OssImageData;
import huoye.shops.huoye.mine.model.ProductInfo;
import huoye.shops.huoye.operation.model.AddImage;
import huoye.shops.huoye.operation.model.Descript;
import huoye.shops.huoye.operation.model.DetialImgs;
import huoye.shops.huoye.operation.model.ShopCouponsList;
import huoye.shops.huoye.operation.presenter.LimitDiscountPresenter;
import huoye.shops.huoye.operation.view.ILimitDiscountView;
import huoye.shops.utils.PickerViewUtils;
import huoye.shops.utils.StockUtils;

import static huoye.shops.huoye.operation.activity.ManageProductActivity.TYPE_SELECT_SHOP_ATTRIBUTE_HK;
import static huoye.shops.huoye.operation.activity.ManageProductActivity.TYPE_SELECT_SHOP_ATTRIBUTE_LIMIT;
import static huoye.shops.huoye.operation.activity.ManageProductActivity.TYPE_SELECT_SHOP_ATTRIBUTE_LM;
import static huoye.shops.huoye.operation.activity.ManageProductActivity.TYPE_SELECT_SHOP_ATTRIBUTE_NEW_USER;
import static huoye.shops.huoye.operation.activity.ManageProductActivity.TYPE_SELECT_SHOP_ATTRIBUTE_SHOW;
import static huoye.shops.huoye.operation.fragment.ManageProductFragment.TYPE_MANAGE_PRODUCT_ALL;

public class LimitDiscountActivity extends BaseTakePhotoActivity implements ILimitDiscountView {


    private boolean isStartTime;
    private Date StartDate;
    private Date EndDate;


    @BindView(R.id.limit_discount_et_name)
    EditText etName;
    @BindView(R.id.limit_discount_et_price)
    EditText etPrice;
    @BindView(R.id.limit_discount_et_stock)
    EditText etStock;
    @BindView(R.id.limit_discount_ev_custom_discount)
    EditText etDiscount;

    @BindView(R.id.limit_discount_tv_custom_discount)
    TextView tvCustomDiscount;
    @BindView(R.id.limit_discount_tv_select_start_time)
    TextView tvStartTime;
    @BindView(R.id.limit_discount_tv_select_ovrdue_time)
    TextView tvOvrdueTime;
    @BindView(R.id.limit_discount_iv_switch)
    ImageView ivSwitch;


    @BindView(R.id.limit_discount_ll_limit_discount)
    LinearLayout llLimitDiscount;
    @BindView(R.id.limit_discount_ll_new_discount)
    RelativeLayout llNewDiscount;

    @BindView(R.id.limit_discount_sp_new_discount)
    Spinner spDiscount;
    @BindView(R.id.limit_discount_tv_new_discount)
    TextView tvDiscount;


    @BindView(R.id.limit_discount_rv)
    RecyclerView recyclerView;

    @BindView(R.id.limit_discount_rv_descript)
    RecyclerView recyclerViewDescript;
    private LimitDiscountPresenter mLimitDiscountPresenter;
    private ProductInfo productInfo;


    @OnClick(R.id.limit_discount_ll_custom_discount)
    void onCustomDiscountClick() {

    }

    @OnClick(R.id.limit_discount_ll_select_start_time)
    void onStartTimeClick() {
        isStartTime = true;
        timePickerView();
    }

    @OnClick(R.id.limit_discount_ll_select_ovrdue_time)
    void onOvrdueTimeClick() {
        isStartTime = false;
        timePickerView();
    }


    boolean isClickSwicht = false;

    @OnClick(R.id.limit_discount_iv_switch)
    void onSwitchClick() {
        isClickSwicht = !isClickSwicht;
        ivSwitch.setSelected(isClickSwicht);
    }


    @OnClick(R.id.limit_discount_btn_cancel)
    void onCancelClick() {
        finish();
    }

    @BindView(R.id.limit_discount_btn_delete)
    Button btnDelete;

    @OnClick(R.id.limit_discount_btn_delete)
    void onDeleteClick() {
        mLimitDiscountPresenter.delProduct(productId);
    }


    private String productId;
    private String productTile;
    private String salePrise = "0";
    private String saleNum = "0";
    private String isSale;
    private List<String> marjorImg = new ArrayList<>();
    private String disType = "0";// 0：不参与折扣 1：新用户折扣 2：一卡通折扣 3.联盟折扣 4：特权折扣（5折以下） 5:自定义折扣（五折以上）
    private String disNum;
    private String couponId;
    private String limitStart;
    private String limitEnd;


    @OnClick(R.id.limit_discount_btn_save_message)
    void onSaveMessageClick() {
        productTile = etName.getText().toString();
        salePrise = etPrice.getText().toString();
        saleNum = etStock.getText().toString();
        disNum = etDiscount.getText().toString();
        if (!disType.equals("1")) {
            disNum = etDiscount.getText().toString();
        }

        //限时折扣
        if (disType.equals("4")) {
            disNum = etDiscount.getText().toString();
            if (StringUtils.isNotEmpty(disNum)) {
                Integer num = Integer.valueOf(disNum);
                if (num == 0) {
                    makeToast("折扣不能为0");
                    return;
                } else if (num > 5) {
                    makeToast("限时折扣应低于黑卡5折");
                    return;
                }
            }

            Date now = new Date();

            if(StartDate == null){
                makeToast("请选择开始时间");
                return;
            }

            if(EndDate == null){
                makeToast("请选择结束时间");
                return;
            }

            if (!StringUtils.isNotEmpty(limitStart)) {
                limitStart = tvStartTime.getText().toString();
            }

            if (!StringUtils.isNotEmpty(limitEnd)) {
                limitEnd = tvOvrdueTime.getText().toString();
            }

            if (!now.before(StartDate)) {
                makeToast("活动时间不能早于当前时间");
                return;
            }

        }

        if (isClickSwicht) {
            isSale = "1";
        } else {
            isSale = "0";
        }


        List<AddImage> images = adapter.getData();
        if (adapter != null || images != null) {
            for (AddImage image : images) {
                if (StringUtils.isNotEmpty(image.getImageUrl())) {
                    marjorImg.add(image.getImageUrl());
                }
            }
        }



        //上传图文详情
        List<Descript> data = imageTextAdapter.getData();
        if(imageTextAdapter != null || data != null ||data.size() >1) {
            for (int i = 0 ; i < data.size(); i++){
                if(StringUtils.isNotEmpty(data.get(i).getImaPath())){
                    data.get(i).setImgUrl(data.get(i).getImaPath()) ;
                }
            }
        }




        mLimitDiscountPresenter.infoProduct(productId, productTile, salePrise, saleNum, isSale, marjorImg, disType, disNum,
                data, couponId, limitStart, limitEnd);
    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_limit_discount;
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        productInfo = getIntentData();
        productId = productInfo.getProductId();

        mLimitDiscountPresenter = new LimitDiscountPresenter();
        mLimitDiscountPresenter.addTaskListener(this);
        mLimitDiscountPresenter.onStart();


        if (productId.equals("0")) {
            setTitle("新增商品");
            getDisTyep(productInfo.getDisType());
        } else {
            setTitle("编辑");
            setEditProduct();
            getEditDisTyep(productInfo.getDisType());

        }
        showAdapter();
        initializeRecyclerView();


    }


    private void getDisTyep(int type) {
        switch (type) {
            case TYPE_SELECT_SHOP_ATTRIBUTE_HK:
                disType = "2";
                break;
            case TYPE_SELECT_SHOP_ATTRIBUTE_LM:
                disType = "3";
                break;
            case TYPE_SELECT_SHOP_ATTRIBUTE_NEW_USER:
                disType = "1";
                llNewDiscount.setVisibility(View.VISIBLE);
                mLimitDiscountPresenter.getShopGoupons();
                break;
            case TYPE_SELECT_SHOP_ATTRIBUTE_SHOW:
                break;
            case TYPE_SELECT_SHOP_ATTRIBUTE_LIMIT:
                disType = "4";
                llLimitDiscount.setVisibility(View.VISIBLE);
                break;
        }
    }


    private void getEditDisTyep(int type) {
        switch (type) {
            case 0:
                disType = "0";
                break;
            case 1:
                disType = "1";
                llNewDiscount.setVisibility(View.VISIBLE);
                mLimitDiscountPresenter.getShopGoupons();
                break;
            case 2:
                disType = "2";
                break;
            case 3:
                disType = "3";
                break;
            case 4:
                disType = "4";
                llLimitDiscount.setVisibility(View.VISIBLE);
                etDiscount.setText(productInfo.getDiscount());
                tvStartTime.setText(productInfo.getActivityStar());
                tvOvrdueTime.setText(productInfo.getActivityEnd());
                break;
        }
    }


    private void setEditProduct() {
        etName.setText(productInfo.getProductTitle());
        etName.setSelection(productInfo.getProductTitle().length());//将光标移至文字末尾
        BigDecimal moeny = StockUtils.moenyStyle(productInfo.getSalePrize());
        etPrice.setText(moeny + "");
        etStock.setText(productInfo.getSaleCount());
        //etDiscount.setText(productInfo.dis);
        btnDelete.setVisibility(View.VISIBLE);
        //	商品状态（-1：已删除 0：下架 1：上架）
        if (productInfo.getIsSale() == 1) {
            isClickSwicht = true;
            ivSwitch.setSelected(isClickSwicht);
        }


        //如果是店铺商品 ，售价和折扣才能修改 ，如果不是 不能进行修改
        if(productInfo.getTypeIntent() != TYPE_MANAGE_PRODUCT_ALL){
            etPrice.setFocusable(false);
            etPrice.setFocusableInTouchMode(false);

            etDiscount.setFocusable(false);
            etDiscount.setFocusableInTouchMode(false);


        }


    }


    private int max = 6;
    private AddPictureAdapter adapter;
    private List<AddImage> AddImageList = new ArrayList<>();

    private void showAdapter() {
        adapter = new AddPictureAdapter(this);
        if (!productId.equals("0")) {
            List<DetialImgs> faceImgs = productInfo.getFaceImgs();
            if (faceImgs.size() > 0) {
                for (int i = 0; i < faceImgs.size(); i++) {
                    AddImage addImage = new AddImage();
                    addImage.setImageUrl(faceImgs.get(i).getProductImg());
                    addImage.setLocal(false);
                    AddImageList.add(addImage);
                }
                adapter.setData(AddImageList);
            }
        }
        adapter.setMaxCount(max);
        adapter.setOnItemClickListener(new AddPictureAdapter.OnItemClickListener<AddImage>() {
            @Override
            public void onItemClick(AddImage addImage, int position, View view) {
                int count = adapter.getItemCount();
                if (adapter.getListCount() == max) {
                    if (position == max - 1) {
                        return;
                    }
                } else {
                    if (position == count - 1) {
                        takePhoto();
                        isDescript = false;
                        return;
                    }
                }
                List<PrevieImage> images = new ArrayList<>();
                List<AddImage> data = adapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    PrevieImage image = new PrevieImage();
                    String url = APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN + data.get(i).getImageUrl();
                    image.setThumbnailUrl(url);
                    image.setImageViewWidth(view.getWidth());
                    image.setImageViewHeight(view.getHeight());
                    int[] points = new int[2];
                    view.getLocationInWindow(points);
                    image.setImageViewX(points[0]);
                    image.setImageViewY(points[1] - BarUtils.getStatusBarHeight(LimitDiscountActivity.this));
                    images.add(image);
                }
                PrevieImageActivity.onStartActivity(LimitDiscountActivity.this, (ArrayList<PrevieImage>) images, position);
            }
        });
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setAdapter(adapter);
    }


    private String imgPath = "";
    private String imgDescriptPath = "";

    @Override
    public void takeSuccess(TResult result) {
        if (result != null) {
            TImage image = result.getImage();
            //上传单张图片
            String userShopId = UserManager.getInstance().getUserShopId();
            if (isDescript) {
                imgDescriptPath = image.getCompressPath();
                mLimitDiscountPresenter.uploadOssImg(userShopId, "shop", imgDescriptPath);
                imageTextAdapter.getData().get(mPosition).setImgUrl(imgDescriptPath);
                imageTextAdapter.getData().get(mPosition).setLocal(true);
                imageTextAdapter.notifyDataSetChanged();
            } else {
                AddImage img = new AddImage();
                imgPath = image.getCompressPath();
                mLimitDiscountPresenter.uploadOssImg(userShopId, "shop", imgPath);
                img.setPath(imgPath);
                img.setLocal(true);
                if (adapter.getListCount() == 0) {
                    adapter.add(0, img);
                } else {
                    adapter.add(adapter.getListCount(), img);
                }
                adapter.notifyDataSetChanged();
            }

        }
    }


    //判断图文是否为空
    private boolean isNull() {
        List<Descript> list = imageTextAdapter.getData();
        for (int i = 0; i < list.size(); i++) {

            if (!StringUtils.isNotEmpty(list.get(i).getImgDes())) {
                makeToast("请填写商店描述");
                return false;
            }

            if (!StringUtils.isNotEmpty(list.get(i).getImgUrl())) {
                makeToast("请选择商店详情图片");
                return false;
            }

        }
        return true;
    }

    private boolean isDescript;
    private int mPosition;
    private int imageTextMax = 100;
    private ImageTextAdapter imageTextAdapter;

    private void initializeRecyclerView() {
        imageTextAdapter = new ImageTextAdapter(this);
        initData();
        imageTextAdapter.setData(imageTextList);
        imageTextAdapter.setMaxCount(imageTextMax);
        imageTextAdapter.setOnItemClickListener(new ImageTextAdapter.OnItemClickListener<Descript>() {
            @Override
            public void onItemClick(Descript list, int i, View view) {
                int count = imageTextAdapter.getItemCount();
                if (imageTextAdapter.getListCount() == imageTextMax) {
                    if (i == imageTextMax - 1) {
                        return;
                    }
                } else {
                    if (i == count - 1) {
                        boolean b = isNull();
                        if (b) {
                            addData();
                        }
                        return;
                    }
                }
            }

            @Override
            public void onAddImageClick(int position) {
                isDescript = true;
                mPosition = position;
                takePhoto();
            }
        });
        recyclerViewDescript.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewDescript.setAdapter(imageTextAdapter);


    }

    List<Descript> imageTextList = new ArrayList<>();

    private void initData() {
        if (productInfo.getProductId().equals("0")) {
            for (int i = 0; i < 1; i++) {
                imageTextList.add(new Descript());
            }
        } else {
            List<DetialImgs> detialImgs = productInfo.getDetialImgs();
            for (int i = 0; i < detialImgs.size(); i++) {
                Descript descript = new Descript();
                descript.setImgDes(detialImgs.get(i).getDescript());
                descript.setImgUrl(detialImgs.get(i).getProductImg());
                descript.setLocal(false);
                imageTextList.add(descript);
            }
        }

    }

    private void addData() {
        if (imageTextAdapter != null) {
            imageTextAdapter.getData().add(new Descript());
            imageTextAdapter.notifyDataSetChanged();
        }
    }


    TimePickerView pvTime;

    private void timePickerView() {
        Date now = new Date();
        if (pvTime == null) {
            pvTime = PickerViewUtils.showEventYearMonthDayHourMinute(this, new Date(), new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    String time = StockUtils.formatMinuteDate(date);

                    if (!now.before(date)) {
                        makeToast("活动时间不能早于当前时间");
                        return;
                    }


                    if (isStartTime) {
                        if (EndDate != null) {
                            if (!EndDate.before(date)) {
                                tvStartTime.setText(time);
                                StartDate = date;
                                limitStart = time;
                            } else {
                                makeToast("开始时间不能晚于结束时间");
                                return;
                            }
                        }
                        tvStartTime.setText(time);
                        StartDate = date;
                    } else {
                        if (StartDate != null) {
                            if (!date.before(StartDate) && !date.equals(StartDate)) {
                                tvOvrdueTime.setText(time);
                                EndDate = date;
                                limitEnd = time;
                            } else {
                                makeToast("结束时间不能早于开始时间");
                            }
                        } else {
                            makeToast("请先选择开始时间开始时间");
                        }


                    }
                    //  makeToast(DateTimeFormat.formatDate(date));
                }
            });
        }
        pvTime.show();
    }

    @Override
    public void setUploadMore(List<OssImageData> ossImageData) {

    }

    @Override
    public void setUpload(OssImageData ossImageData) {
        if (isDescript) {
            List<Descript> images = imageTextAdapter.getData();
            if (imageTextAdapter == null || images == null || images.size() < 1) {
                return;
            }
            for (Descript image : images) {
                if (image.getImgUrl().equals(imgDescriptPath)) {
                    image.setImaPath(ossImageData.getFilePath());
                }
            }

        } else {
            List<AddImage> images = adapter.getData();
            if (adapter == null || images == null || images.size() < 1) {
                return;
            }
            for (AddImage image : images) {
                if (image.getPath().equals(imgPath)) {
                    image.setImageUrl(ossImageData.getFilePath());
                }
            }

        }
    }

    @Override
    public void getGouponsList(List<ShopCouponsList> lists) {
        List<String> CouponsList = new ArrayList<>();
        for (int i = 0; i < lists.size(); i++) {
            CouponsList.add(lists.get(i).getName());
        }

        ArrayAdapter<String> shopCouponsListArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, CouponsList);
        shopCouponsListArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spDiscount.setAdapter(shopCouponsListArrayAdapter);
        spDiscount.setSelection(0, true);
        couponId = lists.get(0).getId();
        disNum = lists.get(0).getDiscount();
        spDiscount.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                //makeToast(shopCouponsListArrayAdapter.getItem(i));
                disNum = lists.get(i).getDiscount();
                couponId = lists.get(i).getId();

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }
}
